package com.myrpc.consumer.rpc.proxy;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.stereotype.Component;

import com.myrpc.consumer.xml.RpcInterFaceData;

@Component
public class RpcRegistryBean implements BeanDefinitionRegistryPostProcessor {
	
	@Override
	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
		// 需要被代理的接口
		//Class<?> cls = InfoUserRemoteService.class;

		BeanDefinitionBuilder builder;
		try {
			
			//for
			Map<String, String> providerInter = RpcInterFaceData.getProviderInter();
			Iterator<Entry<String, String>> iterator = providerInter.entrySet().iterator();
			while(iterator.hasNext()){
				
				Entry<String, String> entry = iterator.next();
				builder = BeanDefinitionBuilder.genericBeanDefinition(entry.getValue());
				GenericBeanDefinition definition = (GenericBeanDefinition) builder.getRawBeanDefinition();
				definition.getConstructorArgumentValues().addGenericArgumentValue(definition.getBeanClassName());
				//definition.getPropertyValues().add("rpcInterface", definition.getBeanClassName());
				//设置接口的 beanClass 都为 RpcFactoryBean<?>，因为 RpcFactoryBean 实现了 FactoryBean 接口，这样初始化 Bean 时就会调用 getObject 方法
				definition.setBeanClass(RpcFactoryBean.class);
				
				//自动注册
				definition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE);
				// 注册bean名,一般为类名首字母小写
				registry.registerBeanDefinition(entry.getKey(), definition);
			}
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		// TODO Auto-generated method stub

	}

}
